var Spirit_Island = document.querySelector('#Spirit-Island');
var spanContainer = document.querySelector('#Spirit-Island .instruction');
var span = document.querySelector('#Spirit-Island .instruction span');
//指令发送模块
var queue_doms = {
    container: document.querySelector('#instruciton-queue-container'),
    queue: document.querySelector('#instruction-queue'),
    submit_btn: document.querySelector('#queue-btn-submit'),

}


//指令集合模块
var instructions_doms = {
    container: document.querySelector('#instructions-box-container'),
    elevator_container: document.querySelector('#instructions-elevator'),
    dormitory_container: document.querySelector('#instructions-dormitory'),

}

//巡查点传递
var queue_temp = {}




//更新左侧指令集
function updateInstructions() {
    //指令集数据
    // 电梯厅指令集
    const instructions_elevator = Object.keys(map_data.elevator).map((name) => {
        const popup = map_data.elevator[name].popup;
        return {
            'type': 'elevator',
            'name': name,
            'popup': popup,
        };
    });

    // 宿舍指令集
    const instructions_dormitory = Object.keys(map_data.dormitory).map((name) => {
        const popup = map_data.dormitory[name].popup;
        return {
            'type': 'dormitory',
            'name': name,
            'popup': popup.split('：')[1],
            'popupFull': popup,
        };
    })
    //更新指令集：电梯指令集
    instructions_doms.elevator_container.innerHTML = instructions_elevator.map((e) => {

        return `<li data-effect="copy" draggable="true" style="background-color: #14e144;" data-type="${e.type}" data-instruction="${e.name}" data-popup="${e.popup}">${e.popup}</li>`
    }).join('');

    //更新指令集：宿舍指令集
    instructions_doms.dormitory_container.innerHTML = instructions_dormitory.map((e) => {

        return `<li data-effect="copy" draggable="true" style="background-color:#0ecfd9;" data-type="${e.type}" data-instruction="${e.name}" data-popup="${e.popup}" data-popupFull="${e.popupFull}">${e.popup}</li>`
    }).join('');
}
updateInstructions();



/**
 * 函数：设置为active1状态
 */
function setActive1() {
    //容器一半减去span的一半减去Spirit-Island的padding-left
    var offset_ = 0.5 * Spirit_Island.offsetWidth - 50 - 25;
    spanContainer.classList.add('active1');
    spanContainer.style.transform = `translateX(${offset_}px)`;
    queue_doms.submit_btn.style.display = 'block';
    queue_doms.queue.style.background = 'none';
}
/**
 * 函数：取消active1状态
 */
function removeActive1() {
    spanContainer.classList.remove('active1');
    spanContainer.style.transform = `translateX(0px)`;
    queue_doms.submit_btn.style.display = 'none';
    queue_doms.queue.style.background = 'url(./asset/queue_sent_background.png)';
    queue_doms.queue.style.backgroundSize = 'cover';
    //清空指令缓存防止误发送指令
    queue_temp = {};
    //清空发送台的指令
    queue_doms.queue.innerHTML = '';
    updateInstructions();
}


//灵动岛点击事件
spanContainer.onclick = function () {
    //是active1状态
    if (spanContainer.classList.contains('active1')) {
        removeActive1();

    }
    //不是active1状态
    else {

        setActive1();
    }
}
//地图绘制函数
/**
 * 绘制地图
 * 如果不连续则只根据map_data的数据补齐后画线
 * 相邻的点则添加marker并画线
 * @param {json} map_data 地图数据
 * @param {json} queue_array 指令数组
 */
function drawMap(queue_array) {
    //遍历queue_array，根据map_data[type][instruction]更新地图
    for (var i = 0; i < Object.keys(queue_array).length - 1; i++) {
        var type_ = queue_array[Object.keys(queue_array)[i]].type;

        var instruction_ = queue_array[Object.keys(queue_array)[i]].instruction;

        var nextType_ = queue_array[Object.keys(queue_array)[i + 1]].type;

        var nextInstruction_ = queue_array[Object.keys(queue_array)[i + 1]].instruction;

        //如果前后两个mapIndex差值为1，则添加marker并画线
        if (queue_array[Object.keys(queue_array)[i + 1]].mapIndex - queue_array[Object.keys(queue_array)[i]].mapIndex === 1) {
            //添加marker
            addMarker(map_data[type_][instruction_]);
            addMarker(map_data[nextType_][nextInstruction_]);
            //画线
            addPolyline(map_data[type_][instruction_], map_data[nextType_][nextInstruction_]);
        }
        //若不为1，比如第一个mapIndex=1,第二个mapIndex=4,则根据mapIndex把中间缺的补上并画线
        else if (queue_array[Object.keys(queue_array)[i + 1]].mapIndex - queue_array[Object.keys(queue_array)[i]].mapIndex != 1) {
            //只画线
            var mapIndex_ = queue_array[Object.keys(queue_array)[i]].mapIndex;
            var mapIndex_next = queue_array[Object.keys(queue_array)[i + 1]].mapIndex;
            var lastitem = map_data[type_][instruction_];
            addMarker(map_data[type_][instruction_]);
            for (var j = mapIndex_ + 1; j < mapIndex_next + 1; j++) {
                //先根据mapIndex找到map_data中的对应的地址

                var foundItem = null;
                if (j === mapIndex_next - 1) {
                    addMarker(map_data[nextType_][nextInstruction_]);
                }
                // 遍历map_data的不同部分，查找具有指定mapIndex的地点
                for (var section in map_data) {
                    for (var item in map_data[section]) {
                        if (map_data[section][item].mapIndex === j) {
                            foundItem = map_data[section][item];
                            //与前一个地点画线
                            addPolyline(lastitem, foundItem);
                            lastitem = foundItem;

                            break; // 找到后可以提前退出循环
                        }
                    }
                }



            }

        }
        // addPolyline(map_data[type_][instruction_], map_data[nextType_][nextInstruction_]);
    }
}
//更新地图导航
function updateMapNavigation() {
    //更新地图
    //获取指令集，根据map_data和queue_show更新地图

    var queue_show = {};
    var queue_li = queue_doms.queue.children;
    for (var i = 0; i < queue_li.length; i++) {
        queue_show[queue_li[i].dataset.instruction] = {
            type: queue_li[i].dataset.type,
            instruction: queue_li[i].dataset.instruction,
            index: i + 1,
            mapIndex: map_data[queue_li[i].dataset.type][queue_li[i].dataset.instruction].mapIndex,
            itemstate: "unfinished",
        }
    }
    queue_temp = queue_show;

    // console.log(queue_show);

    mapClearAll();
    //绘制地图
    drawMap(queue_show);


}


// 监听queue元素的子元素变化
/**
 * 函数：监听queue元素的子元素变化
 * @param {Array} mutationsList
 * @param {Object} observer
 * @returns {undefined}
 * function:若queue元素的子元素数量为0，则取消active1状态
 * function:若queue元素的子元素数量不为0，则设置active1状态并且地图图层更新
 */
const observer = new MutationObserver(function (mutationsList) {
    for (let mutation of mutationsList) {
        if (mutation.type === 'childList') {

            // 在这里执行您希望触发的操作
            if (queue_doms.queue.children.length === 0) {
                removeActive1();
                mapClearAll();
            } else {

                setActive1();
                if (queue_doms.queue.children.length === 1) {
                    mapClearAll();
                    queue_temp = {};
                    // 显示起点
                    addMarker(map_data[queue_doms.queue.children[0].dataset.type][queue_doms.queue.children[0].dataset.instruction]);
                    queue_temp[queue_doms.queue.children[0].dataset.instruction] = {
                        type: queue_doms.queue.children[0].dataset.type,
                        instruction: queue_doms.queue.children[0].dataset.instruction,
                        index: 1,
                        mapIndex: map_data[queue_doms.queue.children[0].dataset.type][queue_doms.queue.children[0].dataset.instruction].mapIndex,
                        itemstate: "unfinished",
                    }
                } else {
                    //更新地图导航
                    updateMapNavigation();
                }
            }
        }
    }
});

// 配置观察选项
const config = {
    childList: true
};

// 开始观察queue元素
observer.observe(queue_doms.queue, config);



//拖拽
var data_drag = {
    element: 0,
    effect: 'copy',

};
//监听发送模块的拖拽事件
//指令集拖拽到发送
//指令集接收 move in
instructions_doms.container.ondragstart = function (e) {
    data_drag.effect = e.target.dataset.effect;
    data_drag.element = e.target;
    // console.log('start', e.target);
}
instructions_doms.container.ondragover = function (e) {
    e.preventDefault();
}
instructions_doms.container.ondrop = function (e) {
    const dropNode = e.target;

    //该节点可以放置

    if (dropNode.dataset.drop === data_drag.effect) {
        mydata = data_drag.element;
        mydata.dataset.effect = 'copy';
        //给instruction-queue添加li元素
        e.target.appendChild(mydata);
        // console.log('drop', e.target);
    }

}

//发送台拖拽到指令集
//发送台接收指令
queue_doms.queue.ondragstart = function (e) {
    data_drag.effect = e.target.dataset.effect;
    data_drag.element = e.target;
    // console.log('start', e.target);
}
queue_doms.queue.ondragover = function (e) {
    e.preventDefault();
}
queue_doms.queue.ondragenter = function (e) {

    // console.log('enter', e.target);
}
queue_doms.queue.ondrop = function (e) {
    const dropNode = e.target;
    //该节点可以放置
    if (dropNode.dataset.drop === data_drag.effect) {
        mydata = data_drag.element;
        mydata.dataset.effect = 'move';
        //给instruction-queue添加li元素
        queue_doms.queue.appendChild(mydata);
        setActive1();
    }

}


//适配移动端的拖拽？？





//指令发送模块

//监听发送按钮的点击事件
queue_doms.submit_btn.onclick = function () {
    //获取指令集
    var queue_sent = {};

    // var queue_li = queue_doms.queue.children;
    // for (var i = 0; i < queue_li.length; i++) {
    //     queue_sent[queue_li[i].dataset.instruction] = {
    //         type: queue_li[i].dataset.type,
    //         instruction: queue_li[i].dataset.instruction,
    //         index: i + 1,
    //     }
    // }
    queue_sent = queue_temp;
    if (!Object.keys(queue_sent).length) {
        alert('请先添加指令');
        return;
    }
    console.log(queue_sent);
    //在地图上更新图层
    /**
     * 函数：在地图上更新图层
     * 地标
     * 连线
     */

    //发送指令给小车
    fetch('http://139.159.253.19:5010/sent', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                'command': queue_sent,
            })
        })
        .then(response =>
            response.json()
        )
        .then(data => {
            console.log('success for sending command')

        })

    //清空发送台的指令
    queue_doms.queue.innerHTML = '';
    alert('指令已发送');
    //重新刷新指令集
    updateInstructions();
    //获取年月日,比如20231023
    var sent_date = new Date();
    sent_date = sent_date.getFullYear().toString() + (sent_date.getMonth() + 1).toString() + sent_date.getDate().toString();
    //楼层
    var sent_floor = 11
    var sent_mainstate = 'unfinished';
    var sent_queue = JSON.stringify(queue_sent);

    //发送的指令格式
    // {
    //     "F11room01_05": {
    //         "type": "dormitory",
    //         "instruction": "F11room01_05",
    //         "index": 1,
    //         "mapIndex": 0,
    //         "itemstate": "unfinished"
    //     },
    //     "F11room20_24": {
    //         "type": "dormitory",
    //         "instruction": "F11room20_24",
    //         "index": 2,
    //         "mapIndex": 5,
    //         "itemstate": "unfinished"
    //     },
    //     "hall_3": {
    //         "type": "elevator",
    //         "instruction": "hall_3",
    //         "index": 3,
    //         "mapIndex": 10,
    //         "itemstate": "unfinished"
    //     },
    //     "F11room39_44": {
    //         "type": "dormitory",
    //         "instruction": "F11room39_44",
    //         "index": 4,
    //         "mapIndex": 11,
    //         "itemstate": "unfinished"
    //     },
    //     "hall_4": {
    //         "type": "elevator",
    //         "instruction": "hall_4",
    //         "index": 5,
    //         "mapIndex": 14,
    //         "itemstate": "unfinished"
    //     }
    // }

    // 上传消息队列到服务器数据库
    fetch('http://139.159.253.19:5010/save_queue', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                "sent_time": sent_date,
                "floor": sent_floor,
                "mainstate": sent_mainstate,
                "queue": sent_queue


            })
        })
        .then(response =>
            response.json()
        )
        .then(data => {
            console.log('success for sending queue to database')

        })

}




//临时修改：时间：2023年10月8日
/**
 * 函数：发送指令
 * 开始巡查
 * 暂停巡查
 * 结束巡查
 */
//发给小车的指令
var command_container = document.querySelector('#BigCommand');

//监听父元素的点击事件
command_container.onclick = function (e) {
    var command = e.target.dataset.value;
    //发送指令给后端
    fetch('http://139.159.253.19:5010/sent', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                'command': command,
            })
        })
        .then(response =>
            response.json()
        )
        .then(data => {
            console.log('success for sending command')

        })
    alert('指令已发送');
}